package com.jchz.net;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.andview.adapter.ABaseRefreshAdapter;
import com.andview.adapter.BaseRecyclerHolder;
import com.baidu.tts.chainofresponsibility.logger.LoggerProxy;
import com.baidu.tts.client.SpeechSynthesizerListener;
import com.baidu.tts.client.TtsMode;
import com.jchz.net.bean.RoomCompaneBean;
import com.jchz.net.bean.RoomCompaneGroupDetailBean;
import com.jchz.net.bean.RoomCompaneVoiceBean;
import com.jchz.net.bean.RoomScheduleBean;
import com.jchz.net.comhttp.DcodeService;
import com.jchz.net.control.InitConfig;
import com.jchz.net.control.MySyntherizer;
import com.jchz.net.control.NonBlockSyntherizer;
import com.jchz.net.listener.UiMessageListener;
import com.jchz.net.util.AutoCheck;
import com.jchz.net.util.CountDownUtils;
import com.jchz.net.util.DateUtil;
import com.jchz.net.util.OfflineResource;
import com.jchz.net.util.SpUtils;
import com.jchz.net.util.TypeCastHelper;
import com.utils.gyymz.mvp.base.MVPBaseActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.BindView;

public class RoomCopaneActivity extends MVPBaseActivity<RoomCopanePresenter> implements RoomCopaneContract.View {

    @BindView(R.id.id_room_co1)
    RecyclerView idRoomCo1;
    @BindView(R.id.id_room_co2)
    RecyclerView idRoomCo2;
    @BindView(R.id.id_room_rv)
    RecyclerView idRoomRv;
    @BindView(R.id.id_ly_setting)
    LinearLayout lySetting;
    @BindView(R.id.id_ly_setting1)
    LinearLayout lySetting1;
    protected String appId = "11005757";
    protected String appKey = "Ovcz19MGzIKoDDb3IsFFncG1";
    protected String secretKey = "e72ebb6d43387fc7f85205ca7e6706e2";
    protected TtsMode ttsMode = TtsMode.MIX;
    protected String offlineVoice = OfflineResource.VOICE_MALE;
    protected MySyntherizer synthesizer;
    protected Handler mainHandler = new Handler();
    private RoomCompaneAdapter roomCompaneAdapter;
    private List<RoomCompaneBean> roomCompaneAdapterlistData = new ArrayList<>();
    private long refreshTime;


    /**
     * 切换离线发音。注意需要添加额外的判断：引擎在合成时该方法不能调用
     */
    private void loadModel(String mode) {
        offlineVoice = mode;
        OfflineResource offlineResource = mPresenter.createOfflineResource(this, offlineVoice);
        //toPrint("切换离线语音：" + offlineResource.getModelFilename());
        int result = synthesizer.loadModel(offlineResource.getModelFilename(), offlineResource.getTextFilename());
        checkResult(result, "loadModel");
    }


    /**
     * 初始化引擎，需要的参数均在InitConfig类里
     * <p>
     * DEMO中提供了3个SpeechSynthesizerListener的实现
     * MessageListener 仅仅用log.i记录日志，在logcat中可以看见
     * UiMessageListener 在MessageListener的基础上，对handler发送消息，实现UI的文字更新
     * FileSaveListener 在UiMessageListener的基础上，使用 onSynthesizeDataArrived回调，获取音频流
     */
    protected void initialTts() {
        LoggerProxy.printable(true); // 日志打印在logcat中
        // 设置初始化参数
        // 此处可以改为 含有您业务逻辑的SpeechSynthesizerListener的实现类
        SpeechSynthesizerListener listener = new UiMessageListener(mainHandler);
        Map<String, String> params = mPresenter.getParams(this);
        // appId appKey secretKey 网站上您申请的应用获取。注意使用离线合成功能的话，需要应用中填写您app的包名。包名在build.gradle中获取。
        InitConfig initConfig = new InitConfig(appId, appKey, secretKey, ttsMode, params, listener);
        // 如果您集成中出错，请将下面一段代码放在和demo中相同的位置，并复制InitConfig 和 AutoCheck到您的项目中
        synthesizer = new NonBlockSyntherizer(this, initConfig, mainHandler); // 此处可以改为MySyntherizer 了解调用过程
    }


    List<RoomCompaneGroupDetailBean> roomCompaneGroupDetailBeans = new ArrayList<>();

    public void initView() {
        int freshCount = SpUtils.getInstance().getIntValue(AppConfig.KEY_FRESH, 5);
        managerCount = SpUtils.getInstance().getIntValue(AppConfig.KEY_MANAGERCOUNT, 6);
        refreshTime = freshCount * 1000L;
        idRoomCo1.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        idRoomCo1.setLayoutManager(linearLayoutManager);
        idRoomRv.setHasFixedSize(true);
        idRoomRv.setNestedScrollingEnabled(false);
        roomCompaneAdapter = new RoomCompaneAdapter(this, roomCompaneAdapterlistData, R.layout.item_room_copane);
        idRoomCo1.setAdapter(roomCompaneAdapter);

        //RoomCompaneGroupDetailBean roomCompaneGroupDetailBean = AssetsDataUtils.getRoomCompaneGroupDetailBean(getApplicationContext());
        roomDetailAdapter = new RoomDetailAdapter(getApplicationContext(), roomCompaneGroupDetailBeans, R.layout.item_room_type);
        idRoomRv.setHasFixedSize(false);
        GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 1);
        layoutManager.setSmoothScrollbarEnabled(true);
        idRoomRv.setLayoutManager(layoutManager);
        idRoomRv.setNestedScrollingEnabled(false);
        idRoomRv.setAdapter(roomDetailAdapter);

        lySetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSetDeBugDialog();
            }
        });

        lySetting1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSetDeBugDialog();
            }
        });

        //0.5秒之后，每隔2秒做一次run()操作
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_roomcopane;
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        initPermission();
        initialTts();
        initView();
        getRoomSchedule();
        startTimerCount();
    }

    Timer mTimer;
    TimerTask mTimerTask;

    public void startTimerCount() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 100;
                    handlerRomState.sendMessage(message);
                }
            };
        }
        mTimer.schedule(mTimerTask, 0, refreshTime);
    }

    private RoomDetailAdapter roomDetailAdapter;
    Handler handlerRomState = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                mPresenter.getRoomCompaneData();
                mPresenter.getRoomScheduleData();
                mPresenter.getRoomCompaneGroupDetail();
                mPresenter.getRoomCompaneVoice();
            }
        }
    };


    /**
     * destory上次使用的 Timer
     */
    public void destroyTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }

    }


    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<>();
        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }

    /**
     * speak 实际上是调用 synthesize后，获取音频流，然后播放。
     * 获取音频流的方式见SaveFileActivity及FileSaveListener
     * 需要合成的文本text的长度不能超过1024个GBK字节。
     */
    private synchronized void speak(List<RoomCompaneVoiceBean> roomCompaneBeanList) {
        if (roomCompaneBeanList == null || roomCompaneBeanList.size() == 0) {
            return;
        }
        for (int i = 0; i < roomCompaneBeanList.size(); i++) {
            String text1 = roomCompaneBeanList.get(i).getRemark();
            Long endtime = TypeCastHelper.toLong(DateUtil.dataOne(DateUtil.stampToDateFomat(roomCompaneBeanList.get(i).getAddtime())));
            //Long a1 = TypeCastHelper.toLong(DateUtil.dataOne(stampToDateFomat("2018-10-23T15:18:49.52")));
            // Long a2 = TypeCastHelper.toLong(DateUtil.dataOne(stampToDateFomat("2018-10-23T15:28:49.52")));
            // Log.e("TAG  onCreate", "a" + stampToDateFomat("2018-10-23T15:08:49.52"));
            // Log.e("TAG  onCreate", "a1" + stampToDateFomat("2018-10-23T15:18:49.52"));
            // Log.e("TAG  onCreate", "a2" + stampToDateFomat("2018-10-23T15:58:49.52"));
            long currentTime = TypeCastHelper.toLong(DateUtil.dataOne(DateUtil.getCurrentTime_Today()));
            //如果历史消息超过十分钟就不要了
            if (currentTime - endtime >= 60 * 10L) {
                continue;//作用是跳过循环本中剩余的语句而强行执行下一次循环;
            }
            int result = synthesizer.speak(text1);
            Log.e("TAH", "speak" + text1);
            checkResult(result, "speak");
            mPresenter.getRoomCompaneVoiceAdd(roomCompaneBeanList.get(i).getID());
        }
    }


    private void checkResult(int result, String method) {
        if (result != 0) {
            Log.e("TAG", " + result + " + method + " + method + " + "错误码文档:http://yuyin.baidu.com/docs/tts/122 ");
        }
    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showNetWorkErrorView() {

    }

    @Override
    public void getRoomCompaneDataSuccess(String data) {
        roomCompaneAdapterlistData = JSONArray.parseArray(data, RoomCompaneBean.class);
        roomCompaneAdapter.setListData(roomCompaneAdapterlistData);
        idRoomCo1.setAdapter(roomCompaneAdapter);
    }

    @Override
    public void getRoomScheduleDataSuccess(String data) {
        roomSchedulAdapterListData=JSONArray.parseArray(data, RoomScheduleBean.class);
        roomSchedulAdapter.setListData(roomSchedulAdapterListData);
        idRoomCo2.setAdapter(roomSchedulAdapter);
    }

    @Override
    public void getRoomCompaneGroupDetailSuccess(String data) {
        roomCompaneGroupDetailBeans = JSONArray.parseArray(data, RoomCompaneGroupDetailBean.class);
        roomDetailAdapter.setListData(roomCompaneGroupDetailBeans);
        idRoomRv.setAdapter(roomDetailAdapter);
    }

    @Override
    public void getRoomCompaneVoiceSuccess(String data) {
        List<RoomCompaneVoiceBean> roomCompaneBeanList = JSONArray.parseArray(data, RoomCompaneVoiceBean.class);
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                speak(roomCompaneBeanList);
            }
        }, 0);
    }


    public class RoomDetailChildAdapter extends ABaseRefreshAdapter<RoomCompaneGroupDetailBean.DetailsBean> {

        private SparseArray<CountDownUtils> countDownMap = new SparseArray<>();

        public RoomDetailChildAdapter(Context context, List<RoomCompaneGroupDetailBean.DetailsBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder,
                               RoomCompaneGroupDetailBean.DetailsBean roomCompaneVoiceBean, int position) {
            LinearLayout relativeLayoutRoot = baseRecyclerHolder.getView(R.id.id_ry_root);
            LinearLayout relativeLayoutRoot1 = baseRecyclerHolder.getView(R.id.id_ry_root1);
            relativeLayoutRoot.setVisibility(View.VISIBLE);
            relativeLayoutRoot1.setVisibility(View.VISIBLE);
            if (roomCompaneVoiceBean.getStatus().equals("1")) {
                relativeLayoutRoot.setVisibility(View.VISIBLE);
                relativeLayoutRoot1.setVisibility(View.GONE);
                relativeLayoutRoot.setBackground(getResources().getDrawable(R.drawable.button_background_border1));
            } else if (roomCompaneVoiceBean.getStatus().equals("-1")) {
                relativeLayoutRoot.setVisibility(View.GONE);
                relativeLayoutRoot1.setVisibility(View.VISIBLE);
                relativeLayoutRoot1.setBackground(getResources().getDrawable(R.drawable.button_background_border2));
            } else {
                relativeLayoutRoot.setBackground(getResources().getDrawable(R.drawable.button_background_border));
                relativeLayoutRoot.setVisibility(View.VISIBLE);
                relativeLayoutRoot1.setVisibility(View.GONE);
            }
            TextView tvCanCallTime = baseRecyclerHolder.getView(R.id.id_tv_time);
            if (!TextUtils.isEmpty(roomCompaneVoiceBean.getServiceEndTime())) {
                long convertSeconds = TypeCastHelper.toLong(DateUtil.dataOne(roomCompaneVoiceBean.getServiceEndTime())) -
                        TypeCastHelper.toLong(DateUtil.dataOne(DateUtil.getCurrentTime_Today()));
                CountDownUtils countDownUtils = null;
                int length = countDownMap.size();
                if (length > 0) {
                    for (int i = 0; i < length; i++) {
                        countDownUtils = countDownMap.get(tvCanCallTime.hashCode());
                        if (countDownUtils != null) {
                            countDownUtils.releaseAll();
                        }
                    }
                }
                refreshTime(convertSeconds, tvCanCallTime);
            }
            //  baseRecyclerHolder.setText(R.id.id_tv_time, roomCompaneVoiceBean.getCardNO());
            baseRecyclerHolder.setText(R.id.id_tv_typeName, roomCompaneVoiceBean.getCardNO());
            baseRecyclerHolder.setText(R.id.id_tv_no, roomCompaneVoiceBean.getCardNO());
            baseRecyclerHolder.setText(R.id.id_tv_state, roomCompaneVoiceBean.getStatusName());
            baseRecyclerHolder.setText(R.id.id_tv_sex, roomCompaneVoiceBean.getSex());
            baseRecyclerHolder.setText(R.id.id_tv_cardid, roomCompaneVoiceBean.getRID() + "");
            baseRecyclerHolder.setText(R.id.id_tv_roomid, roomCompaneVoiceBean.getRoomCode() + "");
        }

        public void refreshTime(long convertSeconds, TextView tvCanCallTime) {
            CountDownUtils countDownUtils = new CountDownUtils(convertSeconds, tvCanCallTime);
            countDownUtils.startCount();
            countDownMap.put(tvCanCallTime.hashCode(), countDownUtils);
        }


    }

    public class RoomDetailAdapter extends ABaseRefreshAdapter<RoomCompaneGroupDetailBean> {
        public RoomDetailAdapter(Context context, List<RoomCompaneGroupDetailBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder, RoomCompaneGroupDetailBean roomCompaneVoiceBean, int i) {
            baseRecyclerHolder.setText(R.id.id_type_name, roomCompaneVoiceBean.getGroupName());
            RecyclerView recyclerViewType = baseRecyclerHolder.getView(R.id.id_ry_type);
            List<RoomCompaneGroupDetailBean.DetailsBean> details = roomCompaneVoiceBean.getDetails();
            RoomCompaneGroupDetailBean.DetailsBean detailsBean = new RoomCompaneGroupDetailBean.DetailsBean();
            detailsBean.setStatus("-1");
            detailsBean.setCardNO(roomCompaneVoiceBean.getGroupName() + "\n" + "(" + details.size() + ")");
            details.add(0, detailsBean);
            RoomDetailChildAdapter roomDetailAdapter = new RoomDetailChildAdapter(getApplicationContext(), details, R.layout.item_room_child_type1);
            recyclerViewType.setHasFixedSize(false);
            recyclerViewType.setNestedScrollingEnabled(false);
            //设置每个item间距
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(), managerCount);
            gridLayoutManager.setSmoothScrollbarEnabled(true);
            recyclerViewType.setLayoutManager(gridLayoutManager);
            recyclerViewType.setAdapter(roomDetailAdapter);

        }

    }

    private int managerCount = 0;

    public void setRyManagerTypeCount(int number) {
        managerCount = number;
    }

    RoomScheduleAdapter roomSchedulAdapter;
    List<RoomScheduleBean> roomSchedulAdapterListData = new ArrayList<>();

    public void getRoomSchedule() {

        idRoomCo2.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        idRoomCo2.setLayoutManager(linearLayoutManager);
        idRoomCo2.setNestedScrollingEnabled(false);
        roomSchedulAdapter = new RoomScheduleAdapter(this, roomSchedulAdapterListData, R.layout.item_room_scedule);
        idRoomCo2.setAdapter(roomSchedulAdapter);
    }


    /**
     * 预约安排
     */
    public class RoomScheduleAdapter extends ABaseRefreshAdapter<RoomScheduleBean> {
        public RoomScheduleAdapter(Context context, List<RoomScheduleBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder, RoomScheduleBean roomScheduleBean, int position) {
            LinearLayout linearLayoutRoot = baseRecyclerHolder.getView(R.id.id_root_ly);
            if (position % 2 == 0) //判断条件错误
            {
                for (int i = 0; i < linearLayoutRoot.getChildCount(); i++) {
                    View childAt = linearLayoutRoot.getChildAt(i);
                    if (childAt instanceof TextView) {
                        ((TextView) childAt).setTextColor(getResources().getColor(R.color.red));
                    }
                }
            } else {
                for (int i = 0; i < linearLayoutRoot.getChildCount(); i++) {
                    View childAt = linearLayoutRoot.getChildAt(i);
                    if (childAt instanceof TextView) {
                        ((TextView) childAt).setTextColor(getResources().getColor(R.color.green));
                    }
                }
            }
            baseRecyclerHolder.setText(R.id.id_tv_ghid, unformat(roomScheduleBean.getCardNOS()));
            baseRecyclerHolder.setText(R.id.id_tv_fhid, unformat(roomScheduleBean.getRoomCodeS()));
            baseRecyclerHolder.setText(R.id.id_tv_people, roomScheduleBean.getInsertMen() + "");
            baseRecyclerHolder.setText(R.id.id_tv_fwtime, DateUtil.stampToDate(roomScheduleBean.getInsertTime()) + "");
        }
    }

    public String unformat(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        if (str.indexOf(",") == 0) {
            //数据处理
            str = str.substring(str.indexOf(",") + 1, str.length() - 1);
        }
        return str;
    }


    /**
     * 语音播报
     */
    public class RoomCompaneAdapter extends ABaseRefreshAdapter<RoomCompaneBean> {
        public RoomCompaneAdapter(Context context, List<RoomCompaneBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder baseRecyclerHolder, RoomCompaneBean roomCompaneVoiceBean, int position) {

            LinearLayout linearLayoutRoot = baseRecyclerHolder.getView(R.id.id_root_ly);
            if (position % 2 == 0) //判断条件错误
            {
                for (int i = 0; i < linearLayoutRoot.getChildCount(); i++) {
                    View childAt = linearLayoutRoot.getChildAt(i);
                    if (childAt instanceof TextView) {
                        ((TextView) childAt).setTextColor(getResources().getColor(R.color.red));
                    }
                }
            } else {
                for (int i = 0; i < linearLayoutRoot.getChildCount(); i++) {
                    View childAt = linearLayoutRoot.getChildAt(i);
                    if (childAt instanceof TextView) {
                        ((TextView) childAt).setTextColor(getResources().getColor(R.color.green));
                    }
                }
            }
            baseRecyclerHolder.setText(R.id.id_tv_xhid, roomCompaneVoiceBean.getRID() + "");
            baseRecyclerHolder.setText(R.id.id_tv_ghid, roomCompaneVoiceBean.getCardNO() + "");
            baseRecyclerHolder.setText(R.id.id_tv_fhid, roomCompaneVoiceBean.getRoomCode() + "");
            baseRecyclerHolder.setText(R.id.id_tv_fwxm, roomCompaneVoiceBean.getItemName() + "");
            baseRecyclerHolder.setText(R.id.id_tv_fwtype, roomCompaneVoiceBean.getClockType() + "");
            baseRecyclerHolder.setText(R.id.id_tv_fwtime, DateUtil.stampToDate(roomCompaneVoiceBean.getServiceStartTime()));
        }

    }


    private static final int RECYCLERVIEWRollROLL = 1;
    private Handler mRecyclerViewHandler;
    private AtomicBoolean shouldContinue = new AtomicBoolean(false);
    private Thread thread = null;

    /**
     * RecyclerView条目的滚动操作
     */
    private void initScroll() {
        /**主线程的handler，用于执行Marquee的滚动消息*/
        mRecyclerViewHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case RECYCLERVIEWRollROLL:
                        /**垂直移动偏移2个像素*/
                        idRoomCo1.smoothScrollBy(0, 10);
                        /**如果移动到底部*/
                        if (isSlideToBottom(idRoomCo1)) {
                            // Log.i("TAG, "滑动到了底部");
                            /**跳至顶部*/
                            idRoomCo1.scrollToPosition(0);
                            /**如果没有移动到底部*/
                            // stopMarquee();
                        } else {
                            // Log.i(TAG, "没有滑动到底部");
                        }
                        break;
                }
            }
        };

        if (thread == null) {
            thread = new Thread() {
                public void run() {
                    while (shouldContinue.get()) {
                        /**每次滚动睡眠0.2秒*/
                        SystemClock.sleep(200);
                        mRecyclerViewHandler.sendEmptyMessage(RECYCLERVIEWRollROLL);
                    }
                    /**退出循环时清理handler*/
                    mRecyclerViewHandler = null;
                }
            };
        }
    }

    @Override
    /**在附到窗口的时候开始滚动*/
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        shouldContinue.set(true);
        initScroll();
        thread.start();
    }

    /**
     * 判断Recycler是否滑动至最底部  是返回true  不是返回false
     */
    public static boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }

    @Override
    /**在脱离窗口时处理相关内容*/
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopMarquee();
    }

    /**
     * 停止滚动
     */
    public void stopMarquee() {
        shouldContinue.set(false);
        thread = null;
    }


    /**
     * 暂停播放。仅调用speak后生效
     */
    private void pause() {
        // int result = synthesizer.pause();
        //  checkResult(result, "pause");
    }

    /**
     * 继续播放。仅调用speak后生效，调用pause生效
     */
    private void resume() {
        // int result = synthesizer.resume();
        // checkResult(result, "resume");
    }


    @Override
    protected void onResume() {
        super.onResume();
        resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pause();
    }

    /*
     * 停止合成引擎。即停止播放，合成，清空内部合成队列。
     */
    private void stop() {
        int result = synthesizer.stop();
        checkResult(result, "stop");
    }


    @Override
    protected void onDestroy() {
        synthesizer.release();
        super.onDestroy();
    }

    @Override
    protected RoomCopanePresenter getDelegateClass() {
        return new RoomCopanePresenter();
    }


    private void showSetDeBugDialog() {
        AlertDialog.Builder setDeBugDialog = new AlertDialog.Builder(this);
        //获取界面
        View dialogView = LayoutInflater.from(this).inflate(R.layout.system_admin_psw_alert_dialog, null);
        //设置自定义界面的点击事件逻辑
        EditText edIp = dialogView.findViewById(R.id.id_ed_ip);
        EditText edClassy = dialogView.findViewById(R.id.id_tv_classy);
        EditText edFresh = dialogView.findViewById(R.id.id_ed_fresh);
        EditText edCount = dialogView.findViewById(R.id.id_ed_count);
        String classy = SpUtils.getInstance().getString(AppConfig.KEY_CLAYSS);
        String baseIp = SpUtils.getInstance().getString(AppConfig.KEY_IP);
        int freshCount = SpUtils.getInstance().getIntValue(AppConfig.KEY_FRESH, 5);
        if (!TextUtils.isEmpty(classy)) {
            edClassy.setText(classy);
        }
        if (!TextUtils.isEmpty(baseIp)) {
            edIp.setText(baseIp);
        }
        if (freshCount != 0) {
            edFresh.setText(freshCount + "");
        }
        //将界面填充到AlertDiaLog容器
        setDeBugDialog.setView(dialogView);
        setDeBugDialog.setCancelable(false);
        //创建AlertDiaLog
        setDeBugDialog.create();
        final AlertDialog customAlert = setDeBugDialog.show();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) dialogView.findViewById(R.id.id_ly_root).getLayoutParams();
        layoutParams.gravity = Gravity.CENTER;
        RadioButton mMaleNv = dialogView.findViewById(R.id.male_nv);
        RadioButton mFamaleNan = dialogView.findViewById(R.id.famale_nan);
        RadioButton mFamaleXY = dialogView.findViewById(R.id.famale_xiaoyao);
        List<String> listClassy = new ArrayList<>();
        StringBuffer setText = new StringBuffer();
        if (!TextUtils.isEmpty(classy)) {
            String[] split = classy.split(",");
            for (int i = 0; i < split.length; i++) {
                listClassy.add(split[i]);
            }
        }
        //复选框
        CheckBox cb_zy = dialogView.findViewById(R.id.cb_zy);
        cb_zy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    listClassy.add("足浴");
                } else {

                }
            }
        });

        CheckBox cb_ys = dialogView.findViewById(R.id.cb_ys);
        cb_ys.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    listClassy.add("养生");
                }

            }
        });

        CheckBox cb_xx = dialogView.findViewById(R.id.cb_xx);
        cb_xx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    listClassy.add("小项");
                }
            }
        });

        CheckBox cb_spa = dialogView.findViewById(R.id.cb_spa);
        cb_spa.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    listClassy.add("SPA");
                }
            }
        });
        cb_zy.setChecked(false);
        cb_ys.setChecked(false);
        cb_xx.setChecked(false);
        cb_spa.setChecked(false);
        if (listClassy.size() > 0) {
            for (int i = 0; i < listClassy.size(); i++) {
                if (listClassy.get(i).contains("足浴")) {
                    cb_zy.setChecked(true);
                }
                if (listClassy.get(i).contains("养生")) {
                    cb_ys.setChecked(true);
                }
                if (listClassy.get(i).contains("小项")) {
                    cb_xx.setChecked(true);
                }
                if (listClassy.get(i).contains("SPA")) {
                    cb_spa.setChecked(true);
                }
            }
        }


        dialogView.findViewById(R.id.system_admin_psw_alert_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                destroyTimer();
                if (!TextUtils.isEmpty(edIp.getText().toString())) {
                    if (!AutoCheck.isIPAddress(edIp.getText().toString())) {
                        Toast.makeText(getApplicationContext(), "请输入合法IP", Toast.LENGTH_LONG).show();
                        return;
                    }
                    SpUtils.getInstance().saveString(AppConfig.KEY_BASEURL, "http://" + edIp.getText().toString() + "/api/Room/");
                    SpUtils.getInstance().saveString(AppConfig.KEY_IP, edIp.getText().toString());
                    DcodeService.changeApiBaseUrl("http://" + edIp.getText().toString() + "/api/Room/");
                }
                String classyStr = edClassy.getText().toString();
                if (!TextUtils.isEmpty(classyStr)) {
                    //判断是否以指定内容结束
                    if (classyStr.endsWith("，") || classyStr.endsWith(",")) {
                        classyStr = classyStr.substring(0, classyStr.length() - 1);
                    }
                    SpUtils.getInstance().saveString(AppConfig.KEY_CLAYSS, classyStr);
                }

                if (!TextUtils.isEmpty(edFresh.getText().toString())) {
                    SpUtils.getInstance().setIntValue(AppConfig.KEY_FRESH, Integer.valueOf(edFresh.getText().toString()));
                    refreshTime = Integer.valueOf(edFresh.getText().toString()) * 1000L;
                }

                if (!TextUtils.isEmpty(edCount.getText().toString())) {
                    managerCount = Integer.valueOf(edCount.getText().toString());
                    SpUtils.getInstance().setIntValue(AppConfig.KEY_MANAGERCOUNT, managerCount);
                    setRyManagerTypeCount(managerCount);
                }

                if (mMaleNv.isChecked()) {
                    loadModel(OfflineResource.VOICE_FEMALE);
                }
                if (mFamaleNan.isChecked()) {
                    loadModel(OfflineResource.VOICE_MALE);
                }
                if (mFamaleXY.isChecked()) {
                    loadModel(OfflineResource.VOICE_DUXY);
                }
                startTimerCount();
                customAlert.dismiss();
            }
        });
        dialogView.findViewById(R.id.sap_alert_dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customAlert.dismiss();
            }
        });

    }

}
